<template>
    <div>
      <section v-for="(groupValue, groupKey) in groupList" :key="groupKey">
        <header class="record-header">
          <span class="pr10">{{groupKey}}</span>
          <span>销售额: ￥</span><span v-big-number="reduce(groupValue, 'sale')" class="pr10"></span>
          <span>收益: ￥</span><span v-big-number="reduce(groupValue, 'income')" class="pr10"></span>
        </header>
        <main class="record-list">
          <div v-for="order in groupValue" :key="order.id" class="record-item">
            <div class="order-left">
              <div class="order-sale">成交金额 : <span v-big-number="order.sale"></span></div>
              <div class="order-date">{{order.date | timeAgo}}</div>
            </div>
            <div class="order-income">+<span v-big-number="order.income"></span></div>
          </div>
        </main>
      </section>
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import moment from 'moment'
import * as _ from 'lodash'
export default {
  name: 'Record',
  metaInfo: {
    title: '往来记录'
  },
  computed: {
    ...mapState({
      list: state => state.record.list // 往来列表
    }),
    // 对list进行分组
    groupList () {
      const groupProp = _.property('date') // 分组依据
      let determineGroup = value => { // 分组
        const now = moment().startOf('month')
        if (value.isSame(now, 'month')) {
          return '本月'
        }
        if (value.isSame(now, 'year')) {
          return value.format('MM月')
        }
        return value.format('YYYY年MM月')
      }
      let groupedData = _
        .chain(this.list)
        .groupBy(datum => determineGroup(moment(groupProp(datum))))
        .value()
      console.log(groupedData)
      return groupedData
    }
  },
  methods: {
    ...mapActions({
      queryOrderRecords: 'record/QueryOrderRecords',
      resetOrderRecord: 'record/ResetOrderRecord',
      setRecordsUserId: 'record/SetRecordsUserId'
    }),
    reduce (collection, property) {
      return _.reduce(collection, (sum, order) => {
        return sum + order[property]
      }, 0)
    }
  },
  created () {
    this.setRecordsUserId(this.$route.query.userId)
    this.queryOrderRecords()
  },
  beforeDestroy () {
    console.log('beforeDestroy')
    this.resetOrderRecord()
  }
}
</script>

<style scoped lang="stylus">
  .record-header
    height 80px
    line-height 80px
    font-size 22px
    color #999
    background #efeef4
    text-align center
    border-bottom 1px solid #d7d6db
  .pr10
    padding-right 10px
  .record-list
    padding-left 30px
  .record-item
    display flex
    padding-top 16px
    padding-bottom 16px
    border-bottom 1px solid #d7d6db
    &:last-child
      border-bottom-color transparent
  .order-left
    flex 1
  .order-sale
    color #333
    font-size 22px
  .order-date
    color #999
    font-size 18px
  .order-income
    color #e79040
    font-size 36px
    padding-right 30px
    display flex
    align-items center
</style>
